package internal

import (
	"context"
	"time"
)

func RunInterval(runDuration time.Duration, interval time.Duration, intervalFn func()) {
	ti := time.NewTimer(interval)
	var runDurationCh <-chan time.Time
	if runDuration > 0 {
		runTicker := time.NewTicker(runDuration)
		runDurationCh = runTicker.C
	} else {
		runDurationCh = make(<-chan time.Time)
	}

	for {
		select {
		case <-runDurationCh:
			return
		case <-ti.C:
			intervalFn()
			ti.Reset(interval)
		}
	}
}

func RunContextAndInterval(ctx context.Context, interval time.Duration, intervalFn func()) {
	ti := time.NewTimer(interval)
	for {
		select {
		case _ = <-ctx.Done():
			return
		case <-ti.C:
			intervalFn()
			ti.Reset(interval)
		}
	}
}
